{% extends "base.html" %}

{% block title %}添加成绩 - 校园生活助手{% endblock %}

{% block css %}
<style>
    .form-control:focus {
        box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.25);
        border-color: #86b7fe;
    }
    .form-label {
        font-weight: 500;
        color: #495057;
    }
    .form-section {
        margin-bottom: 1.5rem;
    }
    .score-weight-input {
        max-width: 80px;
    }
    .score-value-input {
        max-width: 100px;
    }
    .weight-progress {
        height: 6px;
        border-radius: 3px;
        background-color: #e9ecef;
        margin-top: 6px;
    }
    .weight-progress-bar {
        height: 100%;
        border-radius: 3px;
        background-color: #007bff;
        transition: width 0.3s ease;
    }
    .gpa-calculator {
        background-color: #f8f9fa;
        padding: 1rem;
        border-radius: 0.5rem;
        border: 1px solid #e9ecef;
    }
    .gpa-result {
        font-size: 1.5rem;
        font-weight: 600;
        color: #007bff;
    }
</style>
{% endblock %}

{% block content %}
<div class="row">
    <div class="col-lg-8 offset-lg-2">
        <div class="bg-white rounded-lg shadow-sm p-6">
            <h1 class="text-2xl font-bold text-gray-800 mb-4">
                <i class="fa fa-pencil-square-o mr-2 text-primary"></i>{% if score_id %}编辑成绩{% else %}添加成绩{% endif %}
            </h1>
            
            <!-- 消息提示区域 -->
            {% with messages = get_flashed_messages(with_categories=true) %}
                {% if messages %}
                    {% for category, message in messages %}
                        <div class="alert alert-{{ category }} fade-in mb-4" role="alert">
                            <button type="button" class="close" data-bs-dismiss="alert" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                            {{ message }}
                        </div>
                    {% endfor %}
                {% endif %}
            {% endwith %}
            
            <!-- 添加成绩表单 -->
            <form method="POST" action="{{ url_for('add_score') }}{% if score_id %}?id={{ score_id }}{% endif %}">
                {{ form.hidden_tag() }}
                
                <!-- 基本信息 -->
                <div class="form-section">
                    <h3 class="text-lg font-semibold text-gray-700 mb-3">基本信息</h3>
                    
                    <!-- 课程选择 -->
                    <div class="mb-4">
                        {{ form.course.label(class="form-label") }}
                        {{ form.course(class="form-select") }}
                        {% if form.course.errors %}
                            <div class="text-danger mt-1">
                                {% for error in form.course.errors %}
                                    <small>{{ error }}</small>
                                {% endfor %}
                            </div>
                        {% endif %}
                    </div>
                    
                    <!-- 学期 -->
                    <div class="mb-4">
                        {{ form.semester.label(class="form-label") }}
                        {{ form.semester(class="form-select") }}
                        {% if form.semester.errors %}
                            <div class="text-danger mt-1">
                                {% for error in form.semester.errors %}
                                    <small>{{ error }}</small>
                                {% endfor %}
                            </div>
                        {% endif %}
                    </div>
                    
                    <!-- 考试日期 -->
                    <div class="mb-4">
                        {{ form.exam_date.label(class="form-label") }}
                        <div class="input-group">
                            <span class="input-group-text"><i class="fa fa-calendar"></i></span>
                            {{ form.exam_date(class="form-control", type="date") }}
                        </div>
                        {% if form.exam_date.errors %}
                            <div class="text-danger mt-1">
                                {% for error in form.exam_date.errors %}
                                    <small>{{ error }}</small>
                                {% endfor %}
                            </div>
                        {% endif %}
                    </div>
                </div>
                
                <!-- 成绩构成 -->
                <div class="form-section">
                    <h3 class="text-lg font-semibold text-gray-700 mb-3">成绩构成</h3>
                    <p class="text-sm text-gray-500 mb-3">设置各项成绩的权重和分值，总权重必须为100%</p>
                    
                    <div class="space-y-4">
                        <!-- 平时成绩 -->
                        <div class="bg-gray-50 p-4 rounded">
                            <div class="row align-items-center mb-2">
                                <div class="col-3">
                                    <label class="form-label">平时成绩</label>
                                </div>
                                <div class="col-9">
                                    <div class="row">
                                        <div class="col-4">
                                            <div class="input-group">
                                                <input type="number" class="form-control score-weight-input" id="daily_weight" name="daily_weight" value="40" min="0" max="100">
                                                <span class="input-group-text">%</span>
                                            </div>
                                        </div>
                                        <div class="col-4">
                                            <div class="input-group">
                                                <input type="number" class="form-control score-value-input" id="daily_score" name="daily_score" value="{{ form.daily_score.data or 0 }}" min="0" max="100" step="0.5">
                                                <span class="input-group-text">/100</span>
                                            </div>
                                        </div>
                                        <div class="col-4">
                                            <input type="text" class="form-control score-contribution" id="daily_contribution" readonly placeholder="贡献分">
                                        </div>
                                    </div>
                                    <div class="weight-progress">
                                        <div class="weight-progress-bar" id="daily_progress" style="width: 40%"></div>
                                    </div>
                                </div>
                            </div>
                            <div class="text-sm text-gray-500">
                                包括出勤、作业、课堂参与等平时表现
                            </div>
                        </div>
                        
                        <!-- 期中考试 -->
                        <div class="bg-gray-50 p-4 rounded">
                            <div class="row align-items-center mb-2">
                                <div class="col-3">
                                    <label class="form-label">期中考试</label>
                                </div>
                                <div class="col-9">
                                    <div class="row">
                                        <div class="col-4">
                                            <div class="input-group">
                                                <input type="number" class="form-control score-weight-input" id="midterm_weight" name="midterm_weight" value="20" min="0" max="100">
                                                <span class="input-group-text">%</span>
                                            </div>
                                        </div>
                                        <div class="col-4">
                                            <div class="input-group">
                                                <input type="number" class="form-control score-value-input" id="midterm_score" name="midterm_score" value="{{ form.midterm_score.data or 0 }}" min="0" max="100" step="0.5">
                                                <span class="input-group-text">/100</span>
                                            </div>
                                        </div>
                                        <div class="col-4">
                                            <input type="text" class="form-control score-contribution" id="midterm_contribution" readonly placeholder="贡献分">
                                        </div>
                                    </div>
                                    <div class="weight-progress">
                                        <div class="weight-progress-bar" id="midterm_progress" style="width: 20%"></div>
                                    </div>
                                </div>
                            </div>
                            <div class="text-sm text-gray-500">
                                学期中间进行的阶段性考试成绩
                            </div>
                        </div>
                        
                        <!-- 期末考试 -->
                        <div class="bg-gray-50 p-4 rounded">
                            <div class="row align-items-center mb-2">
                                <div class="col-3">
                                    <label class="form-label">期末考试</label>
                                </div>
                                <div class="col-9">
                                    <div class="row">
                                        <div class="col-4">
                                            <div class="input-group">
                                                <input type="number" class="form-control score-weight-input" id="final_weight" name="final_weight" value="40" min="0" max="100">
                                                <span class="input-group-text">%</span>
                                            </div>
                                        </div>
                                        <div class="col-4">
                                            <div class="input-group">
                                                <input type="number" class="form-control score-value-input" id="final_score" name="final_score" value="{{ form.final_score.data or 0 }}" min="0" max="100" step="0.5">
                                                <span class="input-group-text">/100</span>
                                            </div>
                                        </div>
                                        <div class="col-4">
                                            <input type="text" class="form-control score-contribution" id="final_contribution" readonly placeholder="贡献分">
                                        </div>
                                    </div>
                                    <div class="weight-progress">
                                        <div class="weight-progress-bar" id="final_progress" style="width: 40%"></div>
                                    </div>
                                </div>
                            </div>
                            <div class="text-sm text-gray-500">
                                学期结束时进行的总结性考试成绩
                            </div>
                        </div>
                    </div>
                    
                    <!-- 权重总计 -->
                    <div class="mt-4 p-3 bg-primary/5 rounded">
                        <div class="flex justify-between items-center">
                            <span class="font-medium">权重总计:</span>
                            <span class="text-primary font-bold" id="total_weight">100%</span>
                        </div>
                        <div class="mt-1 text-sm text-gray-500">
                            <span id="weight_status" class="text-success">✓ 权重设置正确</span>
                        </div>
                    </div>
                    
                    <!-- 最终成绩预览 -->
                    <div class="mt-4 gpa-calculator">
                        <div class="flex justify-between items-center">
                            <span class="font-medium">最终成绩:</span>
                            <span class="score-value" id="final_total_score">0.0</span>
                        </div>
                        <div class="flex justify-between items-center mt-2">
                            <span class="font-medium">对应绩点:</span>
                            <span class="gpa-result" id="calculated_gpa">0.0</span>
                        </div>
                    </div>
                </div>
                
                <!-- 评价与备注 -->
                <div class="form-section">
                    <h3 class="text-lg font-semibold text-gray-700 mb-3">评价与备注</h3>
                    
                    <!-- 教师评语 -->
                    <div class="mb-4">
                        {{ form.teacher_comments.label(class="form-label") }}
                        {{ form.teacher_comments(class="form-control", rows="3", placeholder="请输入教师评语") }}
                        {% if form.teacher_comments.errors %}
                            <div class="text-danger mt-1">
                                {% for error in form.teacher_comments.errors %}
                                    <small>{{ error }}</small>
                                {% endfor %}
                            </div>
                        {% endif %}
                    </div>
                    
                    <!-- 个人备注 -->
                    <div class="mb-4">
                        {{ form.personal_notes.label(class="form-label") }}
                        {{ form.personal_notes(class="form-control", rows="3", placeholder="请输入个人学习心得或备注") }}
                        {% if form.personal_notes.errors %}
                            <div class="text-danger mt-1">
                                {% for error in form.personal_notes.errors %}
                                    <small>{{ error }}</small>
                                {% endfor %}
                            </div>
                        {% endif %}
                    </div>
                </div>
                
                <!-- 提交按钮 -->
                <div class="mt-6">
                    <button type="submit" class="btn btn-primary mr-2" id="submit-button">
                        <i class="fa fa-save mr-2"></i>保存成绩
                    </button>
                    <a href="{{ url_for('scores') }}" class="btn btn-secondary">
                        <i class="fa fa-arrow-left mr-2"></i>返回成绩列表
                    </a>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
    // 获取DOM元素
    const dailyWeight = document.getElementById('daily_weight');
    const dailyScore = document.getElementById('daily_score');
    const dailyContribution = document.getElementById('daily_contribution');
    const dailyProgress = document.getElementById('daily_progress');
    
    const midtermWeight = document.getElementById('midterm_weight');
    const midtermScore = document.getElementById('midterm_score');
    const midtermContribution = document.getElementById('midterm_contribution');
    const midtermProgress = document.getElementById('midterm_progress');
    
    const finalWeight = document.getElementById('final_weight');
    const finalScore = document.getElementById('final_score');
    const finalContribution = document.getElementById('final_contribution');
    const finalProgress = document.getElementById('final_progress');
    
    const totalWeight = document.getElementById('total_weight');
    const weightStatus = document.getElementById('weight_status');
    const finalTotalScore = document.getElementById('final_total_score');
    const calculatedGpa = document.getElementById('calculated_gpa');
    const submitButton = document.getElementById('submit-button');
    
    // 更新权重进度条
    function updateProgressBars() {
        dailyProgress.style.width = `${dailyWeight.value}%`;
        midtermProgress.style.width = `${midtermWeight.value}%`;
        finalProgress.style.width = `${finalWeight.value}%`;
    }
    
    // 计算各项贡献分
    function calculateContributions() {
        const dailyContrib = (dailyWeight.value * dailyScore.value / 100).toFixed(1);
        const midtermContrib = (midtermWeight.value * midtermScore.value / 100).toFixed(1);
        const finalContrib = (finalWeight.value * finalScore.value / 100).toFixed(1);
        
        dailyContribution.value = dailyContrib;
        midtermContribution.value = midtermContrib;
        finalContribution.value = finalContrib;
        
        return { dailyContrib, midtermContrib, finalContrib };
    }
    
    // 计算总权重
    function calculateTotalWeight() {
        const total = parseInt(dailyWeight.value) + parseInt(midtermWeight.value) + parseInt(finalWeight.value);
        totalWeight.textContent = `${total}%`;
        
        // 检查权重是否正确
        if (total === 100) {
            weightStatus.textContent = '✓ 权重设置正确';
            weightStatus.className = 'text-success';
            submitButton.disabled = false;
        } else {
            weightStatus.textContent = '✗ 权重总和必须为100%';
            weightStatus.className = 'text-danger';
            submitButton.disabled = true;
        }
        
        return total;
    }
    
    // 计算最终成绩
    function calculateFinalScore() {
        const contributions = calculateContributions();
        const total = (parseFloat(contributions.dailyContrib) + parseFloat(contributions.midtermContrib) + parseFloat(contributions.finalContrib)).toFixed(1);
        finalTotalScore.textContent = total;
        
        // 根据成绩设置颜色
        if (total >= 60) {
            finalTotalScore.className = 'score-value pass-score';
        } else {
            finalTotalScore.className = 'score-value fail-score';
        }
        
        return total;
    }
    
    // 计算绩点
    function calculateGpa(score) {
        let gpa = 0;
        
        if (score >= 90) {
            gpa = 4.0;
        } else if (score >= 85) {
            gpa = 3.7;
        } else if (score >= 82) {
            gpa = 3.3;
        } else if (score >= 78) {
            gpa = 3.0;
        } else if (score >= 75) {
            gpa = 2.7;
        } else if (score >= 72) {
            gpa = 2.3;
        } else if (score >= 68) {
            gpa = 2.0;
        } else if (score >= 64) {
            gpa = 1.5;
        } else if (score >= 60) {
            gpa = 1.0;
        } else {
            gpa = 0.0;
        }
        
        calculatedGpa.textContent = gpa.toFixed(1);
        
        return gpa;
    }
    
    // 综合计算函数
    function recalculate() {
        updateProgressBars();
        calculateTotalWeight();
        const finalScoreValue = calculateFinalScore();
        calculateGpa(finalScoreValue);
    }
    
    // 添加事件监听器
    dailyWeight.addEventListener('input', recalculate);
    dailyScore.addEventListener('input', recalculate);
    midtermWeight.addEventListener('input', recalculate);
    midtermScore.addEventListener('input', recalculate);
    finalWeight.addEventListener('input', recalculate);
    finalScore.addEventListener('input', recalculate);
    
    // 初始化计算
    document.addEventListener('DOMContentLoaded', function() {
        recalculate();
        
        // 表单提交前的验证
        document.querySelector('form').addEventListener('submit', function(e) {
            const total = calculateTotalWeight();
            if (total !== 100) {
                e.preventDefault();
                alert('权重总和必须为100%，请重新调整');
                return false;
            }
            
            // 检查各项分数是否在有效范围内
            const scores = [dailyScore.value, midtermScore.value, finalScore.value];
            for (let score of scores) {
                if (score < 0 || score > 100) {
                    e.preventDefault();
                    alert('分数必须在0-100之间');
                    return false;
                }
            }
        });
        
        // 如果是编辑模式，尝试填充现有数据
        {% if score_id %}
            try {
                // 假设后端传递了成绩构成数据
                // 这里是一个示例，实际应用中应该从后端获取数据
                const weight1 = 40; // 示例数据
                const weight2 = 20; // 示例数据
                const weight3 = 40; // 示例数据
                
                dailyWeight.value = weight1;
                midtermWeight.value = weight2;
                finalWeight.value = weight3;
                
                // 重新计算以更新界面
                recalculate();
            } catch (error) {
                console.error('无法加载成绩构成数据:', error);
            }
        {% endif %}
    });
</script>
{% endblock %}